<?php

namespace App\Controller\Api;

use App\Base\BaseController4Restful;
use App\Entity\SharePic;
use App\Repository\SharePicRepository;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Routing\Annotation\Route;

class ApiSharePicController extends BaseController4Restful
{
    /**
     * @Route("/api/sharePics", name="apiGetSharePics",methods={"GET","POST"})
     */
    public function apiGetSharePics(SharePicRepository $repository, Request $request)
    {
        switch ($request->getMethod()) {
            case "POST":
                $data = $this->getRequestData();
                /**@var $SharePic SharePic */
                $SharePic = $this->createEntity($data, SharePic::class);
                $this->myEm()->persist($SharePic);
                $this->myEm()->flush();
                return $this->json_out(200, "创建成功", $SharePic);
            default:
                if (!$page = $this->getParamRequired("page")) {
                    $page = 1;
                }
                $limit = 10;
                $offset = (int)abs($limit * ($page - 1));
                $total = $repository->count([]);
                $this->setMeta($page, $total, $limit);
                $list = $repository->findBy(array(), array(), $limit, $offset);
                return $this->json_out(200, "获取成功", $list);
        }
    }

    /**
     * @Route("/api/sharePics/{id}", name="apiAddSharePics",methods={"GET","PUT","PATCH","DELETE"})
     */
    public function apiUpdateSharePics(SharePic $SharePic, Request $request)
    {
        $data = $this->getRequestData();
        switch ($request->getMethod()) {
            case "DELETE":
                $this->myEm()->remove($SharePic);
                $this->myEm()->flush();
                return $this->json_out(200, "已移除");
            case "PATCH":
            case "PUT":
                /**@var $SharePic SharePic */
                $SharePic = $this->updateEntity($data, SharePic::class, $SharePic);

                $this->myEm()->persist($SharePic);
                $this->myEm()->flush();
                return $this->json_out(200, "修改成功", $SharePic);
                break;
            case "Get":
            default:
        }
        $this->myEm()->persist($SharePic);
        $this->myEm()->flush();
        return $this->json_out(200, "获取成功", $SharePic);
    }
}
